import sys
import os
import fitz
import numpy as np
from PIL import Image

"""
将多页PDF垂直拼接为单张长图
Python 3.13兼容版
版本 Python 3.13.2
pip install numpy pillow PyMuPDF
"""

def convert_pdf_to_long_image(pdf_path, output_path):
    """
    将多页PDF垂直拼接为单张长图
    Python 3.13兼容版
    """
    try:
        # 参数验证
        if not os.path.exists(pdf_path):
            raise FileNotFoundError(f"PDF文件不存在: {pdf_path}")

        if not output_path.lower().endswith(('.png', '.jpg', '.jpeg')):
            output_path += ".jpg"

        # 打开PDF文档
        doc = fitz.open(pdf_path)

        if len(doc) == 0:
            raise ValueError("PDF文档为空")

        # 创建空白长图画布
        max_width = 0
        total_height = 0
        pixmaps = []

        print(f"▸ 开始处理: {pdf_path} ({len(doc)}页)")

        # 第一步：计算总尺寸并渲染每页
        for i in range(len(doc)):
            page = doc.load_page(i)
            zoom = 2  # 高DPI确保清晰度
            matrix = fitz.Matrix(zoom, zoom)
            pix = page.get_pixmap(matrix=matrix, alpha=False)
            pixmaps.append(pix)

            if pix.width > max_width:
                max_width = pix.width
            total_height += pix.height

            print(f"  ▸ 渲染第 {i + 1}/{len(doc)}页 [{pix.width}×{pix.height}]")

        # 创建空白画布
        canvas = Image.new("RGB", (max_width, total_height), "white")

        # 第二步：拼接图片
        y_offset = 0
        for i, pix in enumerate(pixmaps):
            # 转换为PIL图像
            img_data = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.width, 3)
            page_img = Image.fromarray(img_data)

            # 居中放置（如果宽度小于最大宽度）
            if pix.width < max_width:
                x_offset = (max_width - pix.width) // 2
                canvas.paste(page_img, (x_offset, y_offset))
            else:
                canvas.paste(page_img, (0, y_offset))

            y_offset += pix.height

        # 第三步：保存结果
        canvas.save(output_path, quality=95)
        print(f"\n✅ 转换成功! 长图保存至: {os.path.abspath(output_path)}")
        print(f"  尺寸: {max_width}×{total_height} (W×H)")
        return True

    except Exception as e:
        print(f"\n❌ 转换失败: {e}")
        return False


if __name__ == "__main__":
    print("=" * 60)
    print("PDF 转长图工具 (Python 3.13 专用版)")
    print("=" * 60)

    if len(sys.argv) != 3:
        print("使用方法:")
        print(f"  python {os.path.basename(__file__)} <输入PDF路径> <输出图片路径>")
        print("示例:")
        print(f'  python {os.path.basename(__file__)} "C:\\用户\\文档\\报告.pdf" "输出长图.jpg"')
        sys.exit(1)

    success = convert_pdf_to_long_image(sys.argv[1], sys.argv[2])

    if not success:
        print("\n故障排除步骤:")
        print("1. 确保已应用PyMuPDF兼容性修复补丁")
        print("2. 检查PDF文件是否加密或有访问限制")
        print("3. 尝试降级到Python 3.12 (兼容性更好)")
        print("4. 确认文件路径无特殊字符")
        sys.exit(1)